package cn.hiapi.publics.api;

import cn.hiapi.basic.ResponseEntity;
import cn.hiapi.basic.controller.BasicQueryController;
import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.jpa.pageable.PageRequest;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.redis.data.LockConst;
import cn.hiapi.basic.security.TokenGet;
import cn.hiapi.basic.service.BasicService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.basic.wx.IWxService;
import cn.hiapi.basic.wx.WxFactory;
import cn.hiapi.basic.wx.impl.miniprogram.MiniWxService;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.ILockService;
import cn.hiapi.interfaces.config.ConfigConst;
import cn.hiapi.interfaces.config.IConfigService;
import cn.hiapi.interfaces.user.IUserService;
import cn.hiapi.publics.query.ActivityQuery;
import cn.hiapi.publics.vo.ActivityLocationRequest;
import cn.hiapi.publics.vo.ActivityVo;
import cn.hiapi.publics.vo.ShopBaseVo;
import cn.hiapi.shop.entity.shop.Shop;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shop.service.shop.ShopService;
import cn.hiapi.shop.service.shop.vo.ShopDistance;
import cn.hiapi.shop.vo.ActivityInfoVo;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.*;
import cn.hiapi.shopkeeper.entity.order.*;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.service.ActivityNumber;
import cn.hiapi.shopkeeper.service.Shopkeeper;
import cn.hiapi.shopkeeper.service.activity.*;
import cn.hiapi.shopkeeper.service.order.*;
import cn.hiapi.shopkeeper.service.shopkeeper.ActivityPreviewService;
import cn.hiapi.shopkeeper.service.user.HistoryRecordService;
import cn.hiapi.shopkeeper.service.user.SubscribeShopService;
import cn.hiapi.user.dto.BasicUser;
import cn.hiapi.user.entity.InviteCode;
import cn.hiapi.user.entity.User;
import cn.hiapi.user.service.InviteCodeService;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2022/12/16 23:30
 */
@Slf4j
@RestController("publicActivityController")
@RequestMapping("/public/shop/activity")
public class ActivityController extends BasicQueryController<Activity, Long, ActivityVo, ActivityQuery> {

    protected ActivityController(ActivityService basicService, DispatchContext dispatchContext) {
        super(basicService, dispatchContext);
    }


    @ApiOperation(value = "根据坐标查询", notes = "根据坐标查询", nickname = "AdinZ")
    @PostMapping("/location")
    public ResponseEntity<List<ActivityVo>> location(@RequestBody ActivityLocationRequest request) {
        ResponseEntity<List<ShopDistance>> shopDistances = this.dispatchContext.getServiceOne(ShopService.class).locationSearch(null,request.getCid(), request.getLat(), request.getLng(), request.getDistance(), request.getSize(), request.getPage());
        List<ActivityVo> results = new ArrayList<>();
        for (ShopDistance shopDistance : shopDistances.getData()) {
            QueryWrapper wrapper = new QueryWrapper();
//            if (request.getCid() > 0) wrapper.eq("cid", request.getCid());
            wrapper.eq("shopId", shopDistance.getId())
                    .eq("status", 1);
            if (request.getType() != null) wrapper.eq("type", request.getType());
            List<Activity> list = this.dispatchContext.getServiceOne(ActivityService.class).findList(wrapper);
            if (list.isEmpty()) continue;
            List<ActivityVo> items = list.stream().map(e -> {
                ActivityVo vo = e.copy(new ActivityVo());
                vo.setStatus(e.getStatus());
                ShopBaseVo shop = shopDistance.copy(new ShopBaseVo());
                if (shopDistance.getDistance() != null)
                    shop.setDistance(shopDistance.getDistance().getValue());
                vo.setShop(shop);
                Object basic = this.dispatchContext.getServiceOne(ActivityFactory.class).get(e.getType()).getByAid(e.getId());
                JSONObject expand = JSON.parseObject(JSON.toJSONString(basic));
//                if (e.getType() == ActivityType.LOTTERY) {
//                    expand.put("items", this.dispatchContext.getServiceOne(ActivityLotteryItemService.class).getByAid(e.getId()));
//                }
                vo.setExpand(expand);

                ActivityNumber.Total total = this.dispatchContext.getServiceOne(ActivityNumber.class).get(e.getType(), e.getId());
                vo.setSales(total.getSales());
                vo.setParticipate(total.getParticipate());

                return vo;
            }).collect(Collectors.toList());
            results.addAll(
                    items
            );
        }
        return toSuccess(results, shopDistances.getTotal() != null ? shopDistances.getTotal() : 0L, shopDistances.getTotalPage());
    }


    @Override
    public List<ActivityVo> toListVo(List<Activity> list, String[] fields) {
        return list.stream().map(e -> this.getActivityVo(e, dispatchContext)).collect(Collectors.toList());
    }

    @Override
    public ActivityVo toData(Activity e, String[] fields) {
        ActivityVo vo = getActivityVo(e, this.dispatchContext);
        ActivityOther other = this.dispatchContext.getServiceOne(ActivityOtherService.class).getByAid(e.getId());
        vo.setOther(other);
        Token<Object> token = TokenGet.get();

        if (vo.getType() == ActivityType.VOTE) {
            if (token != null && vo.getExpand() != null) {
                JSONArray others = vo.getExpand().getJSONArray("others");
                List resOthers = new ArrayList();
                for (int i = 0; i < others.size(); i++) {
                    ActivityVoteOther voteO = (ActivityVoteOther) others.get(i);
                    long count = this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).existsVote(e.getId(), token.getFid(), voteO.getOtherId());
                    voteO.setVote(count);
                    resOthers.add(voteO);
                }
                vo.getExpand().put("others", resOthers);
            }
        }
        if (vo.getType() == ActivityType.APPLY && token != null) {
            long count = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(new QueryWrapper()
                    .eq("buyerId", token.getFid()).eq("statusType", 1).eq("aid", vo.getId())
            );
            if (count > 0) {
                vo.setApply(count);
            }
        }


        if (token != null) {
            this.dispatchContext.getServiceOne(ActivityPreviewService.class).preview(token.getFid(), e.getId());
            this.dispatchContext.getServiceOne(SubscribeShopService.class).subscribeShop(token.getFid(),e.getShopId());
        }
        ActivityNumber.Total total = this.dispatchContext.getServiceOne(ActivityNumber.class).get(e.getType(), e.getId());
        vo.setSales(total.getSales());
        vo.setParticipate(total.getParticipate());
        return vo;
    }


    @Override
    public ActivityVo toData(Activity data, String[] fields, HttpServletRequest request) {
        ActivityVo vo = super.toData(data, fields, request);
        if (vo.getType() != ActivityType.LOTTERY) return vo;
        String inviteCode = request.getParameter("inviteCode");
        if (StringUtils.isEmpty(inviteCode)) {
            log.info("[抽奖详情] id:{} 没有包含推荐人", data.getId());
            return vo;
        }
        Token<User> token = TokenGet.get();
        if (token == null) {
            log.info("[抽奖详情] id:{} 账号没登录 :{}", data.getId(), inviteCode);
            return vo;
        }
        String lock = LockConst.getLock("activity-data-invite", inviteCode);
        try {
            boolean lock1 = this.dispatchContext.getServiceOne(ILockService.class).lock(lock);
            if (lock1 == false) {
                log.info("[抽奖详情] id:{} 被锁操作", data.getId());
                return vo;
            }
            InviteCode inviteGet = this.dispatchContext.getServiceOne(InviteCodeService.class).inviteGet(inviteCode);
            if (inviteGet == null) {
                log.info("[抽奖详情] id:{} 推荐人不存在 :{}", data.getId(), inviteCode);
                return vo;
            }
            if(inviteGet.getUid()==token.getFid())return vo;
            //当前账号已经被 这个邀请码分享获得过次数了,再次分享就没得次数了
            long newGift = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).count(new QueryWrapper()
                    .eq("inviteUid", inviteGet.getUid())
                    .eq("aid", data.getId())
                    .eq("uid", token.getFid()));
            log.info("[抽奖详情] id:{} 当前账号:{}已经被分享次数:{} ,{}", data.getId(), token.getData().getMobile(), newGift, inviteCode);
            if (newGift == 0) {
                ActivityOther other = this.dispatchContext.getServiceOne(ActivityOtherService.class).getByAid(data.getId());
                log.info("[抽奖详情] id:{} 其他参数  {}", data.getId(), other);
                if (other == null) return vo;
                if (other.getDayShare() <= 0) return vo; //每天分享次数
                if (other.getShareLottery() <= 0) return vo; //分享一人可得次数
                long count = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).todayInviteCount(inviteGet.getUid(), data.getId());
                log.info("[抽奖详情] id:{} 今日分享给你用户次数:{}", data.getId(), count);
                if (count >= other.getDayShare()) return vo;
                for (int i = 0; i < other.getShareLottery(); i++) {
                    log.info("[抽奖详情] id:{} UID:{} 获得抽奖次数:{}/{}", data.getId(), inviteGet.getUid(),other.getShareLottery(),i);
                    ActivityInviteRecord record = new ActivityInviteRecord();
                    record.setType(ActivityType.LOTTERY);
                    record.setInviteUid(inviteGet.getUid());
                    record.setAid(data.getId());
                    record.setUid(token.getFid());
                    record.setNewGift(0);
                    record.setRemark("分享给用户, 用户打开后奖励分享者(" + other.getShareLottery() + ")次 (" + i + ")  邀请码:" + inviteCode);
                    this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).save(record);
                }
            }
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }

        return vo;
    }

    static ActivityVo getActivityVo(Activity e, DispatchContext dispatchContext) {
        ActivityVo vo = e.copy(new ActivityVo());
        vo.setStatus(e.getStatus());
        Shop shop = dispatchContext.getServiceOne(ShopService.class).get(e.getShopId());
        if (shop != null) vo.setShop(shop.copy(new ShopBaseVo()));
        ActivityCategory category = dispatchContext.getServiceOne(ActivityCategoryService.class).get(e.getCid());
        if (category != null) vo.setCategory(category.getName());
        JSONObject expand = dispatchContext.getServiceOne(ActivityFactory.class).get(e.getType()).getExpand(e.getId());
        vo.setExpand(expand);
        ActivityNumber.Total total = dispatchContext.getServiceOne(ActivityNumber.class).get(e.getType(), e.getId());
        vo.setSales(total.getSales());
        vo.setParticipate(total.getParticipate());
        return vo;
    }

    @Override
    protected void detailCallback(Activity data) {
        super.detailCallback(data);

    }

    @ApiOperation(value = "最新砍价领取记录", notes = "最新砍价领取记录", nickname = "AdinZ")
    @GetMapping("/bargain-list")
    public ResponseEntity<List> bargainList(@RequestParam("aid") long aid,
                                            @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                            @RequestParam(value = "size", required = false, defaultValue = "20") int size) {
        ResponseEntity<List<ActivityBargainOrder>> response = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).findPage(new QueryWrapper().eq("aid", aid), PageRequest.of(page, size, Sort.Direction.DESC, "id"));
        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getBuyerId());
            JSONObject object = JsonUtils.builder()
                    .put("bid", e.getId())
                    .put("buyer", base)
                    .put("created", e.getCreated()) //领取时间
                    .build();
            return object;
        }).collect(Collectors.toList());
        return toSuccess(collect, response.getTotal(), response.getTotalPage());
    }

    @ApiOperation(value = "砍价优惠金额", notes = "砍价优惠金额", nickname = "AdinZ")
    @GetMapping("/bargain-discount")
    public ResponseEntity bargainDiscount(@RequestParam("aid") long aid) {
        Token<Object> token = TokenGet.get();
        ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(aid, token.getFid());
        if (order == null) return toSuccess(new ActivityBargainRecordService.Total());
        ActivityBargainRecordService.Total total1 = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).total(order.getId());
        return toSuccess(total1);
    }


    @ApiOperation(value = "砍价进度", notes = "最新砍价领取记录", nickname = "AdinZ")
    @GetMapping("/bargain-progress")
    public ResponseEntity bargainProgress(@RequestParam("bid") long bid) {
        ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(bid);
        if (order == null) return toError("订单不存在");
        Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(order.getAid());
        if (activity == null) return toError("活动不存在");

        ActivityBargainRecordService.Total total = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).total(order.getId());
        JSONObject object = JsonUtils.builder()
                .put("thumb", activity.getThumb())
                .put("title", activity.getTitle())
                .put("expire", activity.getUseEnd()) //结束时间
                .put("costPrice", activity.getPrice()) //原价
                .put("cutPrice", total.getTotalPrice())
                .put("minPrice", order.getMinPrice())
                .put("status", order.getStatus())
                .put("aid", order.getAid())
                .build();
        object.put("uid", order.getBuyerId());
        return toSuccess(object);
    }


    @ApiOperation(value = "砍价记录", notes = "砍价记录", nickname = "AdinZ")
    @GetMapping("/bargain-record")
    public ResponseEntity<List> groupList(@RequestParam("bid") long aid,
                                          @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                          @RequestParam(value = "size", required = false, defaultValue = "20") int size) {
        ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(aid);
        if (order == null) return toError("没有砍价活动");
        ResponseEntity<List<ActivityBargainRecord>> response = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).findPage(new QueryWrapper().eq("oid", order.getId()),
                PageRequest.of(page, size, Sort.Direction.DESC, "id"));
        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getUid());
            return JsonUtils.builder()
                    .put("user", base)
                    .put("price", e.getPrice())//砍价金额
                    .put("created", e.getCreated())//砍价时间
                    .build();
        }).collect(Collectors.toList());
        return toSuccess(collect, response.getTotal(), response.getTotalPage());
    }


    @ApiOperation(value = "接龙记录", notes = "接龙记录", nickname = "AdinZ")
    @GetMapping("/solitaire-record")
    public ResponseEntity solitaireRecord(@RequestParam("aid") long aid,
                                          @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                          @RequestParam(value = "size", required = false, defaultValue = "20") int size) {
        Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(aid);
        if (activity == null) return to404();
        ActivitySolitaire solitaire = (ActivitySolitaire) this.dispatchContext.getServiceOne(ActivityFactory.class).get(activity.getType()).getByAid(activity.getId());
        if (solitaire == null) return to404();

        final List<ActivitySolitaireItem> itemList = this.dispatchContext.getServiceOne(ActivitySolitaireItemService.class).listByAid(activity.getId());
        ResponseEntity<List<ActivitySolitaireOrder>> response = this.dispatchContext.getServiceOne(ActivitySolitaireOrderService.class).findPage(new QueryWrapper().eq("aid", aid), PageRequest.of(page, size, Sort.Direction.DESC, "id"));
        List<JSONObject> collect = response.getData().stream().map(e -> JsonUtils.builder()
                .put("buyer", this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getBuyerId()))
                .put("created", e.getCreated())
                .build()).collect(Collectors.toList());
        JSONObject build = JsonUtils.builder().build();
        build.put("list", collect);
        long buyUser = this.dispatchContext.getServiceOne(ActivityOrderService.class).totalBuyUser(aid);
        build.put("total", buyUser);


        Optional<ActivitySolitaireItem> optional = itemList.stream().filter(e -> e.getCount() <= buyUser).sorted(Comparator.comparing(ActivitySolitaireItem::getCount).reversed()).findFirst();

        if (optional.isPresent()) {
            ActivitySolitaireItem item = optional.get();
            build.put("rate", item.getRate());
            build.put("index", item.getIndex());
        } else build.put("rate", 0d);
        return toSuccess(build, response.getTotal(), response.getTotalPage());
    }


    @ApiOperation(value = "最新抽奖记录", notes = "最新抽奖记录", nickname = "AdinZ")
    @GetMapping("/latest-lottery")
    public ResponseEntity latestLottery(@RequestParam("size") int size,
                                        @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                        @RequestParam(value = "aid", required = false) Long aid) {

        QueryWrapper wrapper = new QueryWrapper().eq("lotteryState", 1);
        if (aid != null) wrapper.eq("aid", aid);
        ResponseEntity<List<ActivityLotteryOrder>> response = this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class)
                .findPage(wrapper, PageRequest.of(page, size, Sort.Direction.DESC, "id"));


        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getBuyerId());
            return JsonUtils.builder()
                    .put("user", base)
                    .put("title", e.getTitle())
                    .put("thumb", e.getThumb())
                    .put("price", e.getPrice())
                    .put("aid", e.getAid())
                    .put("created", e.getCreated())
                    .build();
        }).collect(Collectors.toList());
        return toSuccess(collect, response.getTotal(), response.getTotalPage());
    }

    @ApiOperation(value = "投票排名", notes = "投票排名", nickname = "AdinZ")
    @GetMapping("/vote-rank")
    public ResponseEntity activityVoteRanking(@RequestParam("aid") long aid, @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        List<JSONObject> list = this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).activityRank(aid);
        List<ActivityVoteOther> others = this.dispatchContext.getServiceOne(ActivityVoteOtherService.class).findByAid(aid);

        Optional<BigInteger> optional = list.stream().map(e -> JsonUtils.getBigInteger(e, "count")).reduce(BigInteger::add);

        final BigInteger totalCount = optional.isPresent() ? optional.get() : BigInteger.ONE;

        list.forEach(e -> {
            long otherId = e.getLongValue("otherId");
            for (ActivityVoteOther other : others) {
                if (other.getOtherId() == otherId) {
                    e.put("title", other.getTitle());
                    e.put("thumb", other.getThumb());
                }
            }
            BigDecimal rate = BigDecimal.valueOf(JsonUtils.getLong(e, "count")).divide(new BigDecimal(totalCount), 10, RoundingMode.HALF_EVEN).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_EVEN);
            e.put("rate", rate);
        });
        return toSuccess(list);
    }


    @ApiOperation(value = "我的中奖记录", notes = "我的中奖记录", nickname = "AdinZ")
    @GetMapping("/lottery-record")
    public ResponseEntity lotteryRecord(@RequestParam("aid") long aid) {

        QueryWrapper wrapper = new QueryWrapper().eq("lotteryState", 1);
        wrapper.eq("aid", aid);
        ResponseEntity<List<ActivityLotteryOrder>> response = this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class)
                .findPage(wrapper, PageRequest.of(1, 20, Sort.by(Sort.Direction.DESC, "id")));
        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getBuyerId());
            return JsonUtils.builder()
                    .put("user", base)
                    .put("title", e.getTitle())
                    .put("thumb", e.getThumb())
                    .put("price", e.getPrice())
                    .put("aid", e.getAid())
                    .put("created", e.getCreated())
                    .build();
        }).collect(Collectors.toList());
        return toSuccess(collect);
    }


    @ApiOperation(value = "用户邀请记录", notes = "用户邀请记录", nickname = "AdinZ")
    @GetMapping("/invite-record")
    public ResponseEntity inviteRecord(@RequestParam("aid") long aid, @RequestParam(value = "page", required = false, defaultValue = "1") int page) {

        Token<Object> token = TokenGet.get();

        if (token == null) return toSuccess(Lists.newArrayList());
        QueryWrapper wrapper = new QueryWrapper()
                .eq("aid", aid);
        wrapper.eq("inviteUid", token.getFid());
        ResponseEntity<List<ActivityInviteRecord>> response = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).findPage(wrapper, PageRequest.of(page, 20, Sort.Direction.DESC, "id")
        );
        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object user = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getInviteUid());
            return JsonUtils.builder()
                    .put("amount", e.getShareAmount())
                    .put("created", e.getCreated())
                    .put("user", user)
                    .build();
        }).collect(Collectors.toList());
        ResponseEntity<List<JSONObject>> responseEntity = toSuccess(collect, response.getTotal(), response.getTotalPage());
        return responseEntity;
    }


    @GetMapping("/share")
    public ResponseEntity share(@RequestParam("aid") long aid, HttpServletResponse response) throws IOException {
        String property = this.dispatchContext.getServiceOne(Environment.class).getProperty("spring.profiles.active");
        if (StringUtils.equalsAnyIgnoreCase(property, "dev")) {
            return toError("开发环境不支持");
        }
        Activity activity = basicService.get(aid);
        if (activity == null) return toError("活动不存在");
        BasicEntity expand = this.dispatchContext.getServiceOne(ActivityFactory.class).get(activity.getType()).getByAid(activity.getId());

        Shop shop = this.dispatchContext.getServiceOne(ShopService.class).get(activity.getShopId());

        JSONObject config = this.dispatchContext.getServiceOne(IConfigService.class).getConfig(0, ConfigConst.CONFIG_WX_PROGRAM);

        MiniWxService wxService = (MiniWxService) this.dispatchContext.getServiceOne(WxFactory.class).getService(config);


        String path = "pages_activity/group/group_dateils";
        switch (activity.getType()) {
            case CARD:
                path = "pages/store/card_datalis";
                break;
            case LOTTERY_AD:
            case LOTTERY:
                path = "pages/draw/draw_index";
                break;
        }
        Token<Object> token = TokenGet.get();
        long uid = shop.getUid();
        if (token != null) uid = token.getFid();
        if(activity.getType()==ActivityType.LOTTERY) {
            ActivityLottery lottery= (ActivityLottery) expand;
            if (lottery.getTemplate() == 1) {
                activity.setThumb("https://shopkeeper-sx.oss-cn-hangzhou.aliyuncs.com/upload/2023-03-08/3068552153555333120.png");
            } else {
                activity.setThumb("https://shopkeeper-sx.oss-cn-hangzhou.aliyuncs.com/upload/2023-03-08/3068552240541003776.png");
            }
        }

        InviteCode code = this.dispatchContext.getServiceOne(InviteCodeService.class).getByUid(uid);
        byte[] stream = wxService.generateCode(path, (aid + "@" + (code != null ? code.getCode() : "")), StringUtils.equalsAnyIgnoreCase(property, "dev"));
        Shopkeeper.generateShareImage(activity, expand, shop, stream, response.getOutputStream());
        response.setContentType("image/png");
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return null;
    }


}
